package com.datasecops.scannerservices.operation;

import com.datasecops.scannerservices.db.MongoDBUtil;
import com.datasecops.scannerservices.entity.CommonParam;
import com.datasecops.scannerservices.enumerate.DBType;
import com.datasecops.scannerservices.service.ScanDataProcessServer;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.bson.Document;

import javax.annotation.Resource;
import java.util.*;

/**
  *
  * 非关系型数据库公操作类
  * @Description
  * @author GeXiaoLong
  * @time 2022/10/8 9:17
  * @param
  * @return
  */
@Service
@Slf4j
public class NoSqlDBCommonOperation {

    //每一批次定1000行
    private int batchLine = 1000;

    @Resource
    private ScanDataProcessServer dataProcessServer;


    /**
     * 获取数据库下面所有的表
     *
     * @param
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/18 10:52
     */
    public List<String> getTablesByDBName(CommonParam param, String Instance, String Model){
        String host = param.getIp();
        int port = param.getPort();
        String userName = param.getUserName();
        String password = param.getPassword();
        // 定义MongoDB的连接地址
        ServerAddress serverAddress = new ServerAddress(host, port);

        // 定义MongoDB的认证信息
        MongoCredential credential = MongoCredential.createCredential(userName, Instance, password.toCharArray());

        // 定义MongoDB的连接对象
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));

        // 获取MongoDB的数据库对象
        MongoDatabase database = mongoClient.getDatabase(Instance);

        // 获取MongoDB的集合对象
        //MongoCollection<Document> collection = database.getCollection("testCollection");
        MongoIterable<String> strings = database.listCollectionNames();
        List<String> _list = new ArrayList<>();
        for (String s : strings) {
            MongoCollection<Document> collection = database.getCollection(s);
            long count = collection.count();
            _list.add(s+"."+count);

        }

 /*       // 查询MongoDB数据库，并输出查询结果
        Document document = collection.find().first();
        System.out.println(document.toJson());*/

        // 关闭MongoDB连接
        mongoClient.close();
        return _list;
       /* return MongoDBUtil.getAllCollections(param.getIp(), param.getPort(),param.getUserName(),Instance,param.getPassword());*/
    }

    /**
     * 获取DB数据返回
     *
     * @param
     * @param commonParam
     * @param typeEnum
     * @param jobId
     * @param jobName
     * @param scannerID
     * @param linage
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/16 10:43
     */
    public boolean getDBResult(CommonParam param, String Instance, CommonParam commonParam, DBType typeEnum, String jobId, String jobName, String scannerID, String linage) {

        try {
            LinkedHashMap<String, LinkedList<String>> sourceDataMap =  MongoDBUtil.findAlls(param.getIp(),param.getPort(),param.getUserName(),Instance, param.getPassword(),param.getTableName());
            int count = 0;
            int batch = 0;

            count++;
            if (count % batchLine == 0) {//每1000行，为一个批次
                //数据操作
                batch++;
                //todo
                dataProcessServer.tradingData(param, sourceDataMap, batch, commonParam, typeEnum, jobId, jobName,
                        scannerID, linage);
                sourceDataMap.clear();
            }
            //处理未满一千行的
            if (sourceDataMap.size() > 0) {
                batch++;
                dataProcessServer.tradingData(param,sourceDataMap,batch, commonParam, typeEnum, jobId, jobName, scannerID, linage);
                sourceDataMap.clear();
            }

        } catch (Exception e) {
            log.error("Failed Method getDBResult error :" + e.getMessage());
            return false;
        } finally {
            //MongoDBUtil.close();
        }
        return true;
    }
}



